package com.example.buletooth_spp;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;

import java.nio.ByteBuffer;

@SuppressLint("UseSwitchCompatOrMaterialCode")
public class MainActivity extends AppCompatActivity {

    private Menu menu = null;

    private BlueToothStream blueTooth;
//    private EditText editText;
//
//    private Switch switchLight;
//
//    private SeekBar seekBarFanSpeed;
//    private SeekBar seekBarRangeHoodSpeed;
//
//    private TextView curTem;
//    private TextView curHum;
//    private TextView curMQ2;
//    private TextView curMQ135;
//
//    private Switch temWarningFlag;
//    private Switch humWarningFlag;
//    private Switch mq2WarningFlag;
//    private Switch mq135WarningFlag;
//
//    private EditText temWarningData;
//    private EditText humWarningData;
//    private EditText mq2WarningData;
//    private EditText mq135WarningData;
    private UiData deviceData;

    private final BroadcastReceiver connectFlagReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null)
            {
                if (action.equals(BlueToothSelectTools.CONNECT_ENABLE))     //蓝牙连接
                {
                    MainActivity.this.blueTooth.startListening(deviceData.getHandler());

                    deviceData.setAllDeviceIsEnable(true);
                }
                else if (action.equals(BlueToothSelectTools.CONNECT_DISABLE))       //蓝牙停止
                {
                    deviceData.setAllDeviceIsEnable(false);
                }
            }
        }
    };

//    void updateUi()
//    {
//        this.switchLight            .setChecked(this.deviceData.getRecDataFrame().isLightState());
//
//        this.seekBarFanSpeed        .setProgress(this.deviceData.getRecDataFrame().getFanSpeed());
//        this.seekBarRangeHoodSpeed  .setProgress(this.deviceData.getRecDataFrame().getRangeHoodSpeed());
//
//        this.curTem                 .setText(String.valueOf(this.deviceData.getRecDataFrame().getCurNums()[0]));
//        this.curHum                 .setText(String.valueOf(this.deviceData.getRecDataFrame().getCurNums()[1]));
//        this.curMQ2                 .setText(String.valueOf(this.deviceData.getRecDataFrame().getCurNums()[2]));
//        this.curMQ135               .setText(String.valueOf(this.deviceData.getRecDataFrame().getCurNums()[3]));
//
//        this.temWarningFlag         .setChecked(this.deviceData.getRecDataFrame().getWarningOpenFlags()[0]);
//        this.humWarningFlag         .setChecked(this.deviceData.getRecDataFrame().getWarningOpenFlags()[1]);
//        this.mq2WarningFlag         .setChecked(this.deviceData.getRecDataFrame().getWarningOpenFlags()[2]);
//        this.mq135WarningFlag       .setChecked(this.deviceData.getRecDataFrame().getWarningOpenFlags()[3]);
//
//        this.temWarningData         .setText(String.valueOf(this.deviceData.getRecDataFrame().getWarningNums()[0]));
//        this.humWarningData         .setText(String.valueOf(this.deviceData.getRecDataFrame().getWarningNums()[1]));
//        this.mq2WarningData         .setText(String.valueOf(this.deviceData.getRecDataFrame().getWarningNums()[2]));
//        this.mq135WarningData       .setText(String.valueOf(this.deviceData.getRecDataFrame().getWarningNums()[3]));
//    }
//
//    void initUi()
//    {
//        this.switchLight            = findViewById(R.id.switch_LightFlag);
//        this.seekBarFanSpeed        = findViewById(R.id.seekBar_Fan_Speed);
//        this.seekBarRangeHoodSpeed  = findViewById(R.id.seekBar_RangeHood_Speed);
//        this.curTem                 = findViewById(R.id.text_tem_data);
//        this.curHum                 = findViewById(R.id.text_hum_data);
//        this.curMQ2                 = findViewById(R.id.text_mq2_data);
//        this.curMQ135               = findViewById(R.id.text_mq135_data);
//        this.temWarningFlag         = findViewById(R.id.switch_TemWarningFlag);
//        this.humWarningFlag         = findViewById(R.id.switch_HumWarningFlag);
//        this.mq2WarningFlag         = findViewById(R.id.switch_MQ2WarningFlag);
//        this.mq135WarningFlag       = findViewById(R.id.switch_MQ135WarningFlag);
//        this.temWarningData         = findViewById(R.id.edit_tem_warning);
//        this.humWarningData         = findViewById(R.id.edit_hum_warning);
//        this.mq2WarningData         = findViewById(R.id.edit_mq2_warning);
//        this.mq135WarningData       = findViewById(R.id.edit_mq135_warning);
//        this.editText               = findViewById(R.id.editTextText2);
//
//        this.switchLight            .setEnabled(false);
//        this.seekBarFanSpeed        .setEnabled(false);
//        this.seekBarRangeHoodSpeed  .setEnabled(false);
//        this.curTem                 .setEnabled(false);
//        this.curHum                 .setEnabled(false);
//        this.curMQ2                 .setEnabled(false);
//        this.curMQ135               .setEnabled(false);
//        this.temWarningFlag         .setEnabled(false);
//        this.humWarningFlag         .setEnabled(false);
//        this.mq2WarningFlag         .setEnabled(false);
//        this.mq135WarningFlag       .setEnabled(false);
//        this.temWarningData         .setEnabled(false);
//        this.humWarningData         .setEnabled(false);
//        this.mq2WarningData         .setEnabled(false);
//        this.mq135WarningData       .setEnabled(false);
//
//    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //动态申请位置权限3
        this.requestPermission();
        this.blueTooth = new BlueToothStream(this);

        Button button = findViewById(R.id.btn_bluetoothSendPack);

        this.deviceData = new UiData(this);

        registerReceiver(this.connectFlagReceiver, new IntentFilter(BlueToothSelectTools.CONNECT_ENABLE));
        registerReceiver(this.connectFlagReceiver, new IntentFilter(BlueToothSelectTools.CONNECT_DISABLE));

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ByteBuffer buffer = ByteBuffer.allocate(32);
//                buffer.put((byte) 1);                               //灯
//                buffer.putShort((short) -500);                      //风扇转速
//                buffer.putShort((short) -500);                      //风机转速
//                buffer.put((byte) 1);                               //温度报警flag
//                buffer.put((byte) 1);                               //湿度报警flag
//                buffer.put((byte) 1);                               //燃气报警flag
//                buffer.put((byte) 1);                               //烟雾报警flag
//                buffer.put(convertFloatToHalfFloat(60.1f));         //温度报警阈值
//                buffer.put(convertFloatToHalfFloat(90.1f));         //湿度报警阈值
//                buffer.put(convertFloatToHalfFloat(6.1f));          //燃气报警阈值
//                buffer.put(convertFloatToHalfFloat(6.1f));          //烟雾报警阈值
//                blueTooth.bluetoothSendPack(buffer.array());
//                //flag = (byte) (flag == 1 ? 0 : 1);
            }
        });

        deviceData.startListener();

        //显示SDK版本
        Toast.makeText(this, Build.VERSION.SDK_INT + "", Toast.LENGTH_SHORT).show();
    }

    //加载菜单资源文件
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu, menu);
        this.menu = menu;

        return true;
    }

    //处理菜单项的点击事件。
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.scan_spp)
        {
            if(!this.blueTooth.getBlueToothStates())      //蓝牙未开启
            {
                //申请开启蓝牙
                this.blueTooth.turnOnBlueTooth(this, BlueToothSelectTools.REQUEST_CODE);
            }
            else {
                //建立连接
                this.blueTooth.connect();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private void requestPermission() {
        //动态申请是否有必要看sdk版本
        if (Build.VERSION.SDK_INT < 23){return;}
        //判断是否有权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }

    public static byte[] convertFloatToHalfFloat(float value) {
        // 将4字节浮点数转换为16位浮点数
        int floatBits = Float.floatToIntBits(value);
        int sign = (floatBits >> 16) & 0x8000; // 符号位
        int exponent = ((floatBits >> 23) & 0xFF) - 112; // 指数位
        int mantissa = floatBits & 0x7FFFFF; // 尾数

        if (exponent <= 0) {
            // 如果指数小于等于0，返回0
            return new byte[]{(byte) (sign >> 8), (byte) (sign & 0xFF)};
        } else if (exponent >= 0x1F) {
            // 如果指数大于等于31，返回无穷大
            return new byte[]{(byte) ((sign | 0x7C00) >> 8), (byte) ((sign | 0x7C00) & 0xFF)};
        } else {
            // 根据指数和尾数构造16位浮点数
            exponent = Math.min(exponent, 0x1F);
            mantissa >>= 13; // 保留10位尾数
            int halfFloatBits = sign | (exponent << 10) | mantissa;
            return new byte[]{
                    (byte) (halfFloatBits >> 8),  // 高字节
                    (byte) (halfFloatBits & 0xFF)  // 低字节
            };
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        this.blueTooth.onDestroy();
        unregisterReceiver(this.connectFlagReceiver);
    }

    public Menu getMenu() {
        return menu;
    }

    public BlueToothStream getBlueTooth() {
        return blueTooth;
    }

    public UiData getDeviceData() {
        return deviceData;
    }

    public BroadcastReceiver getConnectFlagReceiver() {
        return connectFlagReceiver;
    }
}
